/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-24 16:00:01
 * @LastEditTime: 2022-05-25 23:19:39
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 
 */

/* 引入样式 */
import './popup.less'
/* 参数接口 */
interface popupOptions {
  width?: string,
  height?: string,
  title?: string,
  mask?: boolean,
  pos?: string,
  content?: (el: HTMLElement) => void
}
/* 组件方法接口 */
interface componentMethod {
  templateContainer: HTMLElement
  init: () => void,
  template: () => void,
  handle: () => void
}

export default function popup(options: popupOptions) {
  return new Popup(options)
}

class Popup implements componentMethod {
  templateContainer: HTMLElement
  mask: HTMLElement
  constructor(private setting: popupOptions) {
    this.templateContainer = document.createElement('div')
    this.mask = document.createElement('div')
    this.setting = Object.assign({
      width: '100%',
      height: '100%',
      title: '标题',
      mask: true,
      pos: 'center',
      content: function () { }
    }, this.setting)
    this.init()
  }
  init() {
    this.template()
    this.setting.mask && this.createMask()
    this.handle()
    this.contentCallBack()
  }
  template() {
    this.templateContainer.className = 'popup'
    this.templateContainer.style.width = <string>this.setting.width
    this.templateContainer.innerHTML = `<div class='popup-title'>
    <h3>${this.setting.title}</h3>
    <i class='iconfont icon-guanbi'></i>
    </div>
    <div class='popup-body'></div>
    `
    document.body.appendChild(this.templateContainer)
    this.templateContainer.style.top = '50%'
    this.templateContainer.style.transform = 'translateY(-50%)'
    if (this.setting.pos === 'left') {
      this.templateContainer.style.left = '0px'
    }
    else if (this.setting.pos === ' right') {
      this.templateContainer.style.right = '0px'
    }
    else {
      this.templateContainer.style.transform = 'translateY(-50%)'
      this.templateContainer.style.left = (window.innerWidth - this.templateContainer.clientWidth) / 2 + 'px'

    }

  }
  handle() {
    const close = document.querySelector('.popup-title .iconfont')
    close?.addEventListener('click', () => {
      document.body.removeChild(this.templateContainer)
      this.setting.mask && document.body.removeChild(this.mask)
    })
  }
  createMask() {
    this.mask = document.createElement('div')
    this.mask.className = 'popup-mask'
    document.body.appendChild(this.mask)
  }
  contentCallBack() {
    const content = document.querySelector('.popup-body')
    this.setting.content && console.log(this.setting.content);

    this.setting.content ? this.setting.content(<HTMLElement>content) : console.log('');

  }
}